//
//  BaiduMapViewController.m
//  testBaiduMap
//
//  Created by 张金梦 on 16/1/15.
//  Copyright © 2016年 Moon. All rights reserved.
//

#import "BaiduMapViewController.h"


#define MYBUNDLE_NAME @ “mapapi.bundle”

#define MYBUNDLE_PATH [[[NSBundlemainBundle] resourcePath] stringByAppendingPathComponent:MYBUNDLE_NAME]

#define MYBUNDLE [NSBundle bundleWithPath:MYBUNDLE_PATH]

BOOL isRetina = FALSE;

@interface RouteAnnotation :BMKPointAnnotation

{
    
    int _type;
    
    int _degree;
    
}

@property (nonatomic) int type;

@property (nonatomic) int degree;

@end

@implementation RouteAnnotation

@synthesize type = _type;

@synthesize degree = _degree;

@end

@interface UIImage(InternalMethod)

-(UIImage*)imageRotatedByDegrees:(CGFloat)degrees;

@end

@implementation UIImage(InternalMethod)

-(UIImage*)imageRotatedByDegrees:(CGFloat)degrees

{
    
    CGSize rotatedSize = self.size;
    
    if (isRetina) {
        
        rotatedSize.width *= 2;
        
        rotatedSize.height *= 2;
        
    }
    
    UIGraphicsBeginImageContext(rotatedSize);
    
    CGContextRef bitmap =UIGraphicsGetCurrentContext();
    
    CGContextTranslateCTM(bitmap,rotatedSize.width/2, rotatedSize.height/2);
    
    CGContextRotateCTM(bitmap, degrees * M_PI /180);
    
    CGContextRotateCTM(bitmap, M_PI);
    
    CGContextScaleCTM(bitmap, -1.0, 1.0);
    
    CGContextDrawImage(bitmap,CGRectMake(-rotatedSize.width/2, -rotatedSize.height/2,rotatedSize.width, rotatedSize.height), self.CGImage);
    
    UIImage* newImage =UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return newImage;
    
}

@end

@implementation BaiduMapViewController



- (void)viewDidLoad {
   
    [super viewDidLoad];
    [_baiduMapView setZoomLevel:13];
    
    //延迟地理名称搜索
   [self performSelector:@selector(startGeo) withObject:self  afterDelay:1];
    [self startLocation];
    [self performSelector:@selector(startRoute) withObject:self afterDelay:1];
    //[self startRoute];
    _cityname=@"重庆";  //传递的参数
    _endName=@"重庆北站";
    [_placeNameLable setText:_endName];
    
    
    [_schoolMapBtn layoutIfNeeded];
     UIImage *myImage = [UIImage imageNamed:@"schoolArrow"];
    [_schoolMapBtn setImage:[UIImage imageNamed:@"schoolArrow"] forState:UIControlStateNormal];
    [_schoolMapBtn setTitle:@"校内地图" forState:UIControlStateNormal];
    [_schoolMapBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -myImage.size.width, 0, myImage.size.width)];
    [_schoolMapBtn setImageEdgeInsets:UIEdgeInsetsMake(0, _schoolMapBtn.titleLabel.bounds.size.width, 0, -_schoolMapBtn.titleLabel.bounds.size.width)];
    
}

-(void)startRoute
    {
        
        //如果是从当前位置为起始点
        _Routesearcher= [[BMKRouteSearch alloc]init];
        _Routesearcher.delegate=self;
            BMKPlanNode* start = [[BMKPlanNode alloc]init];
            
            _startPt.latitude=_localLatitude;
            
            _startPt.longitude=_localLongitude;
            
            start.pt = _startPt;
            
            start.name = _startName;
            
            BMKPlanNode* end = [[BMKPlanNode alloc]init];
            _startPt.latitude=_endLatitude;
            _startPt.longitude=_endLongitude;
            end.pt = _startPt;
            end.name = _endName;
        
      //  NSLog(@" _localLatitude=%lf__localLongitude=%lfPt.latitude=%lf,_startPt.longitude%lf", _localLatitude,_localLongitude,_startPt.latitude,_startPt.longitude);
           
            BMKDrivingRoutePlanOption *drivingRouteSearchOption = [[BMKDrivingRoutePlanOption alloc]init];
            drivingRouteSearchOption.from = start;
            drivingRouteSearchOption.to = end;
            BOOL flag1 = [_Routesearcher drivingSearch:drivingRouteSearchOption];

            if (!flag1) {
                
                NSLog(@"Drivingsearch failed!");
            }
        

}

//实现Route Deleage处理回调结果
- (void)onGetDrivingRouteResult:(BMKRouteSearch*)searcher result:(BMKDrivingRouteResult*)result errorCode:(BMKSearchErrorCode)error
{
    NSLog(@"onGetDrivingRouteResult:error:%d",error);
    
    NSArray* array = [NSArray arrayWithArray:_baiduMapView.annotations];
    [_baiduMapView removeAnnotations:array];
    array = [NSArray arrayWithArray:_baiduMapView.overlays];
    [_baiduMapView removeOverlays:array];
    
    
    if (error == BMK_SEARCH_NO_ERROR) {
        BMKDrivingRouteLine* plan = (BMKDrivingRouteLine*)[result.routes objectAtIndex:0];
        // 计算路线方案中的路段数目
        NSInteger size = [plan.steps count];
        int planPointCounts = 0;
        for (int i = 0; i < size; i++) {
            BMKDrivingStep* transitStep = [plan.steps objectAtIndex:i];
            if(i==0){
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item.coordinate = plan.starting.location;
                item.title = _startName;
                item.type = 0;
                [_baiduMapView addAnnotation:item]; // 添加起点标注
                
            }else if(i==size-1){
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item.coordinate = plan.terminal.location;
                item.title = _endName;
                item.type = 1;
                [_baiduMapView addAnnotation:item]; // 添加起点标注
            }
            //添加annotation节点
//            RouteAnnotation* item = [[RouteAnnotation alloc]init];
//            item.coordinate = transitStep.entrace.location;
//            item.title = transitStep.entraceInstruction;
//            item.degree = transitStep.direction * 30;
//            item.type = 4;
//            [_baiduMapView addAnnotation:item];
            
            //轨迹点总数累计
            planPointCounts += transitStep.pointsCount;
        }
        // 添加途经点
        if (plan.wayPoints) {
            for (BMKPlanNode* tempNode in plan.wayPoints) {
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item = [[RouteAnnotation alloc]init];
                item.coordinate = tempNode.pt;
                item.type = 5;
                item.title = tempNode.name;
                [_baiduMapView addAnnotation:item];
            }
        }
        //轨迹点
        BMKMapPoint * temppoints = new BMKMapPoint[planPointCounts];
      
        int i = 0;
        for (int j = 0; j < size; j++) {
            BMKDrivingStep* transitStep = [plan.steps objectAtIndex:j];
            int k=0;
            for(k=0;k<transitStep.pointsCount;k++) {
                temppoints[i].x = transitStep.points[k].x;
                temppoints[i].y = transitStep.points[k].y;
                i++;
            }
            
        }
        // 通过points构建BMKPolyline
        BMKPolyline* polyLine = [BMKPolyline polylineWithPoints:temppoints count:planPointCounts];
        [_baiduMapView addOverlay:polyLine]; // 添加路线overlay
        delete []temppoints;
        [self mapViewFitPolyLine:polyLine];
    }
}
- (void)mapViewFitPolyLine:(BMKPolyline *) polyLine {
    CGFloat ltX, ltY, rbX, rbY;
    if (polyLine.pointCount < 1) {
        return;
    }
    BMKMapPoint pt = polyLine.points[0];
    ltX = pt.x, ltY = pt.y;
    rbX = pt.x, rbY = pt.y;
    for (int i = 1; i < polyLine.pointCount; i++) {
        BMKMapPoint pt = polyLine.points[i];
        if (pt.x < ltX) {
            ltX = pt.x;
        }
        if (pt.x > rbX) {
            rbX = pt.x;
        }
        if (pt.y > ltY) {
            ltY = pt.y;
        }
        if (pt.y < rbY) {
            rbY = pt.y;
        }
    }
    BMKMapRect rect;
    rect.origin = BMKMapPointMake(ltX , ltY);
    rect.size = BMKMapSizeMake(rbX - ltX, rbY - ltY);
    [_baiduMapView setVisibleMapRect:rect];
    _baiduMapView.zoomLevel = _baiduMapView.zoomLevel - 0.3;
  
}

#pragma -mark 开始正向地理编码
-(void)startGeo
{
     _searcher =[[BMKGeoCodeSearch alloc]init];
   
     _searcher.delegate = self;
    
    BMKGeoCodeSearchOption *geoCodeSearchOption = [[BMKGeoCodeSearchOption alloc]init];
   // geoCodeSearchOption.city= _cityname;
    geoCodeSearchOption.address =_endName;
    BOOL flag = [_searcher geoCode:geoCodeSearchOption];
    //[geoCodeSearchOption release];
    if(flag)
    {
        NSLog(@"geo检索发送成功");
    }
    else
    {
        NSLog(@"geo检索发送失败");
    }
    
    //发起反向地理编码检索
    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){_localLatitude, _localLongitude};
    BMKReverseGeoCodeOption *reverseGeoCodeSearchOption = [[
    BMKReverseGeoCodeOption alloc]init];
    reverseGeoCodeSearchOption.reverseGeoPoint = pt;
    BOOL flag1 = [_searcher reverseGeoCode:reverseGeoCodeSearchOption];
       if(flag1)
    {
      NSLog(@"反geo检索发送成功");
    }
    else
    {
      NSLog(@"反geo检索发送失败");
    }
}

#pragma -mark 开始定位

-(void)startLocation
{
   
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
   
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8) {
        //由于IOS8中定位的授权机制改变 需要进行手动授权
        CLLocationManager  *locationManager = [[CLLocationManager alloc] init];
        //获取授权认证
        [locationManager requestAlwaysAuthorization];
        [locationManager requestWhenInUseAuthorization];
    }
   
    [_locService startUserLocationService];
    _baiduMapView.showsUserLocation = YES;//显示定位图层
   _baiduMapView.userTrackingMode = BMKUserTrackingModeFollow;//设置定位的状态
    
}

 #pragma -mark 实现定位delegate -处理方向变更信息

- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
  //  NSLog(@"heading is %@",userLocation.heading);
    
    
}
 #pragma -mark 定位坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
   // NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
        [_baiduMapView updateLocationData:userLocation];
   
// self.baiduMapView.centerCoordinate = CLLocationCoordinate2DMake(userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude);
    //以当前位置为起始点
    _localLatitude=userLocation.location.coordinate.latitude;
    _localLongitude= userLocation.location.coordinate.longitude;
}

 #pragma -mark  定位失败
- (void)didFailToLocateUserWithError:(NSError *)error
{
    NSLog(@"location error");
}


 #pragma -mark  实现Deleage处理回调结果-接收正向编码结果

- (void)onGetGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{
    if (error == BMK_SEARCH_NO_ERROR) {
       
        // 添加一个PointAnnotation
        BMKPointAnnotation* annotation = [[BMKPointAnnotation alloc]init];
        CLLocationCoordinate2D coor;
        coor.latitude =result.location.latitude;
        coor.longitude = result.location.longitude;
        annotation.coordinate = coor;
        annotation.title = _endName;
        [self.baiduMapView addAnnotation:annotation];
        
        _endLatitude=coor.latitude;
        _endLongitude=coor.longitude;
      
         NSLog(@"找到地理位置结果");
    }
    else {
        NSLog(@"抱歉，未找到地理位置结果");
    }
    
    
}
//接收反向地理编码结果
-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:
(BMKReverseGeoCodeResult *)result
errorCode:(BMKSearchErrorCode)error{
  if (error == BMK_SEARCH_NO_ERROR) {
     // 在此处理正常结果
      _cityname=result.addressDetail.city;
      _startName=result.address;
      NSLog(@"_startName=%@",_startName);
  }
  else {
      NSLog(@"抱歉，未找到结果");
  }
}

 #pragma -mark 实现地图标注代理方法
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation
{
    if ([annotation isKindOfClass:[BMKPointAnnotation class]]) {
      
        
        BMKPinAnnotationView *newAnnotationView = (BMKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:@"AnnotationView"];
        newAnnotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"AnnotationView"];
        newAnnotationView.pinColor = BMKPinAnnotationColorPurple;
        newAnnotationView.animatesDrop = YES;// 设置该标注点动画显示
        return newAnnotationView;
    }
    return nil;
}
- (BMKOverlayView*)mapView:(BMKMapView *)map viewForOverlay:(id<BMKOverlay>)overlay
{
    if ([overlay isKindOfClass:[BMKPolyline class]]) {
        BMKPolylineView* polylineView = [[BMKPolylineView alloc] initWithOverlay:overlay];
        polylineView.fillColor = [[UIColor alloc] initWithRed:0 green:1 blue:1 alpha:1];
        polylineView.strokeColor = [[UIColor alloc] initWithRed:0 green:0 blue:1 alpha:0.7];
        polylineView.lineWidth = 3.0;
        return polylineView;
    }
    return nil;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

#pragma -mark 控制map 生命周期
- (void)viewWillAppear:(BOOL)animated
{
  
    [_baiduMapView viewWillAppear];
      _baiduMapView.delegate = self;
    

}
-(void)viewWillDisappear:(BOOL)animated
{
   
    _searcher.delegate = nil;
    _locService.delegate = nil;
    _Routesearcher.delegate = nil;
    [_baiduMapView viewWillDisappear];
   _baiduMapView.delegate = nil;
    
}

#pragma -mark  跳转到校内地图
- (IBAction)gotoSchoolMap:(id)sender {
    
}



@end
